/*
 * @lc app=leetcode.cn id=61 lang=javascript
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function (head, k) {
  if (head === null) return head;
  // 获取链表长度
  const getLinkedLength = (head) => {
    let size = 1;
    let temp = head;
    while (temp.next) {
      temp = temp.next;
      size++;
    }
    return size;
  };

  let pre = head;
  let size = getLinkedLength(head);

  // 找到链表尾节点
  while (pre.next) {
    pre = pre.next;
  }
  // 形成环形链表
  pre.next = head;

  // 找到新的链表头的上一个节点 size-k
  // 取模是为了处理k大于size的情况
  let i = 1;
  while (i++ < size - (k % size)) {
    head = head.next;
  }
  // pre指向新的链表头
  pre = head.next;
  // 将环断开
  head.next = null;

  return pre;
};
// @lc code=end
